import 'package:flutter/material.dart';

class CustomCanvas extends StatefulWidget {
  @override
  _CustomCanvasState createState() => _CustomCanvasState();
}

class _CustomCanvasState extends State<CustomCanvas> {
  double offsetX = 0; // 当前偏移量（水平滚动）
  double step = 10; // 100g 间距
  double defaultKg = 5.0; //默认中心点
  double canvasWidth = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: GestureDetector(
          onHorizontalDragUpdate: (details) {
            setState(() {
              offsetX -= details.delta.dx; // 跟随手指拖动
              print('JtTag:details.delta.dx:${offsetX}');
            });
          },
          child: CustomPaint(
            size: Size(MediaQuery.of(context).size.width, 150),
            painter: RulerPainter(offsetX: offsetX, step: step),
          ),
        ),
      ),
    );
  }
}

class RulerPainter extends CustomPainter {
  final double offsetX;
  final double step; //单位间距
  double canvasWidth = 0; //画布总长

  RulerPainter({required this.offsetX, required this.step});

  @override
  void paint(Canvas canvas, Size size) {
    // 总长
    canvasWidth = size.width;
    // 画笔
    final paint = Paint()
      ..color = Colors.black
      ..strokeWidth = 2;
    // 中心点
    final midY = size.height / 2;
    final midX = size.width / 2;
    // 长刻度
    double longTickHeight = 30;
    // 中刻度
    double midTickHeight = 15;
    // 短刻度
    double shortTickHeight = 5;
    // 文本绘制
    final textPainter = TextPainter(
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );

    // 在中间画一个倒三角形指针
    final pointerPaint = Paint()
      ..color = Color(0xFF9860f6)
      ..style = PaintingStyle.fill;

    final double centerX = size.width / 2;
    final double topY = midY + 10; // 三角形顶点高度
    final double baseY = midY - 30; // 三角形底部高度
    final double halfBase = 6; // 三角形底边一半宽度

    final path = Path()
      ..moveTo(centerX, topY) // 顶点
      ..lineTo(centerX - halfBase, baseY) // 左下角
      ..lineTo(centerX + halfBase, baseY) // 右下角
      ..close();

    canvas.drawPath(path, pointerPaint);

    //   右边
    var count = 0;
    for (double x = midX; x < canvasWidth + offsetX; x += step) {
      var tx = x - offsetX;
      if (tx > canvasWidth) {
        print('JtTag:截至右边');
        break;
      }
      if (count % 10 == 0) {
        // 长刻度
        canvas.drawLine(
          Offset(tx, midY),
          Offset(tx, midY + longTickHeight),
          paint,
        );
      } else if (count % 5 == 0) {
        // 中刻度
        canvas.drawLine(
          Offset(tx, midY),
          Offset(tx, midY + midTickHeight),
          paint,
        );
      } else {
        // 短刻度
        canvas.drawLine(
          Offset(tx, midY),
          Offset(tx, midY + shortTickHeight),
          paint,
        );
      }

      count++;
    }
    count = 0;
    //   左边
    for (double x = midX; x > offsetX; x -= step) {
      var tx = x - offsetX;
      if (tx < 0) {
        print('JtTag:截至左边');
        break;
      }
      if (count % 10 == 0) {
        // 画长刻度
        canvas.drawLine(
          Offset(tx, midY),
          Offset(tx, midY + longTickHeight),
          paint,
        );
      } else if (count % 5 == 0) {
        // 画中刻度
        canvas.drawLine(
          Offset(tx, midY + midTickHeight),
          Offset(tx, midY),
          paint,
        );
      } else {
        //  画短刻度
        canvas.drawLine(
          Offset(tx, midY + shortTickHeight),
          Offset(tx, midY),
          paint,
        );
      }
      count++;
    }
    // 画数字
    textPainter.text = TextSpan(
      text: '${((offsetX / 100) + 5.0).toStringAsFixed(1)} kg',
      style: TextStyle(color: Color(0xFF9860f6), fontSize: 16),
    );

    textPainter.layout();
    textPainter.paint(canvas, Offset(midX - textPainter.size.width / 2, 0));
  }

  @override
  bool shouldRepaint(covariant RulerPainter oldDelegate) =>
      oldDelegate.offsetX != offsetX;
}
